package com.ruoyi.project.util;


import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate
 *
 * @author zn kai
 * @create 2020-11-17 15:03
 */
public class RestTemplateUtil {

    /**
     * Content-Type:application/json
     */
    public static final int APPLICATION_JSON = 1;

    /**
     * Content-Type:application/x-www-form-urlencoded
     */
    public static final int APPLICATION_FORM_URLENCODED = 2;

    /**
     * HTTP  request
     *
     * @param <T>
     * @param url         请求地址
     * @param contentType Content-Type
     * @param data        传输数据
     * @param tClass      返回类型
     * @return
     */
    public static <T> T rest(String url, int contentType, String data, Class<T> tClass) {
        HttpHeaders header = new HttpHeaders();
        switch (contentType) {
            case 1:
                header.setContentType(MediaType.APPLICATION_JSON);
                break;
            case 2:
                header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                break;
        }

        HttpEntity<String> request = new HttpEntity<>(data, header);
        //设置超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        /*requestFactory.setConnectTimeout(1000);
        requestFactory.setReadTimeout(2000);*/

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.POST, request, tClass);
        return exchange.getBody();
    }



}
